package com.metadata_system.api_server.socket_server;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.metadata_system.common.dto.JwtToken;

import java.util.HashMap;

@Component
@Slf4j
public class MySocketIOHandler {

    @Autowired
    MyClientUser myClientUser;
    /**
     * 客户端-链接成功
     **/
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        myClientUser.saveClient(client);
//        log.info("新用户,连接建立成功 - " + client.getSessionId());
    }

    /**
     * 客户端-链接关闭
     **/
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        myClientUser.removeClient(client);

//        log.info("连接关闭成功: " + client.getSessionId());
    }


    /**
     * 接收客户端消息-转发
     **/
    @OnEvent("newSocketIO-ClientMessage")
    public void clientMessage(SocketIOClient client, AckRequest ackRequest, MyMessage myMessage) {
        log.info("收到新消息: " + JSON.toJSONString(myMessage));
        client.getSessionId();
        if (StringUtils.isEmpty(myMessage.getPlatform())){
            myMessage.setPlatform("PC");
        }
        JwtToken jwtToken = null;
        try {
            jwtToken=myClientUser.parseToken(myMessage);
        }catch (Exception e){
            client.sendEvent("newSocketIO-ServerMessage", MyMessage.builder()
                    .eventType("LOGIN")
                    .message("ERROR")
                    .build());
            return;
        }
        if (jwtToken==null){
            client.sendEvent("newSocketIO-ServerMessage", MyMessage.builder()
                    .eventType("LOGIN")
                    .message("ERROR")
                    .build());
            return;
        }
        myMessage.setUserId(Integer.valueOf(jwtToken.decodeID()));
        switch (myMessage.getEventType()) {
            case "NORMAL":
                myClientUser.sendMessageToUser(myMessage);
                break;
            case "LOGIN":
                // 加入登录用户map
//                log.info("解析token成功,登录: "+jwtToken.toString());
                myClientUser.loginClient(jwtToken,client,myMessage.getPlatform(),myMessage.getDeviceId());
                // 发送登录成功消息
                HashMap<String, Object> loginUserMap = new HashMap<>();
                loginUserMap.put("username",jwtToken.getUsername());
                loginUserMap.put("role",jwtToken.getRole());
                loginUserMap.put("userId",jwtToken.decodeID());
                client.sendEvent("newSocketIO-ServerMessage", MyMessage.builder()
                        .eventType("LOGIN")
                        .message(JSON.toJSONString(loginUserMap))
                        .build());
                break;
        }
//        HashMap<UUID, SocketIOClient> userClient = clientCache.getUserClient("79");
//        Iterator<Map.Entry<UUID, SocketIOClient>> iterator = userClient.entrySet().iterator();
//        while(iterator.hasNext()){
//            Map.Entry<UUID, SocketIOClient> next = iterator.next();
//            next.getValue().sendEvent("newSocketIO-ServerMessage", message);
//        }
    }
}
